package com.yijinsuo.tool;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

/**
 * Created by ekikousei易皇星 on 16/11/18.
 * E-mail:13764664731@163.com
 * Signature:缘分是本书,翻的不经意会错过,读的太认真会流泪!!
 * <p/>
 * TODO:类描述:
 */
public class SharedPreferencesUtils {

    /**
     * 保存在手机里面的文件名
     */
    private static SharedPreferencesUtils mSpUtils;
    public static final String FILE_NAME = "share_data";


    private SharedPreferencesUtils (){}


    //提供单例  懒汉模式 线程安全
    public static synchronized SharedPreferencesUtils getInstance(){
        if(mSpUtils==null){
            mSpUtils=new SharedPreferencesUtils();
        }
        return mSpUtils;
    }
    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context    上下文
     * @param key        键
     * @param object     值
     */

    public  void put(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (object instanceof String) {
            editor.putString(key, (String) object);

        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);

        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);

        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        // 一定要提交
        editor.commit();

    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param context   上下文
     * @param key       键
     * @param defaultObject  默认值
     * @return
     */
    public Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param context
     * @param key
     */

    public  void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        editor.commit();
    }

    /**
     * 清除所有数据
     *
     * @param context
     */
    public  void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }
    /**
     * 查询某个key是否已经存在
     *
     * @param context     userAccount
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 针对复杂类型存储<对象>  对象一定要实现序列化Serializable
     *
     * @param key
     * @param object
     */


    public static void saveObject(Context context,String key, Object object){

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out=null;
        try {
            out=new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, objectVal);
            editor.commit();


        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *
     *  获取sp保存的对象
     * @param key
     * @param cls
     * @return
     */

    public  <T> T getObject(Context context,String key, Class<T> cls){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        if(sp.contains(key)){
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;

            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (Exception e) {
                // TODO: handle exception
            }finally{
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;

    }

    /**
     * 根据存储的key来查找value是否存在 返回boolean类型
     *
     * @param context
     * @param key
     * @return
     */

   public boolean isLogin(Context context, String key){
       if(contains(context,key)){
           return true;
       }else {
           return false;
       }

   }


    /**
     *
     * @param context
     * @param key
     *
     *   根据key清除value
     */

    public  void  outLogin(Context context, String key){

        remove(context, key);

    }
}
